﻿using Gecko.Models;
using Gecko.Models.Dto;
using Gecko.Services;
using Gecko.Util;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Routing;

namespace Gecko.Controllers
{
    public class ResourceController : ApiController
    {

        // GET api/resource
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/resource/5
        public ServiceResponse<IList<WaterLeakResourceDto>> Get(int waterLeakId)
        {
            using (var waterLeakResourceService = new WaterLeakResourceService())
            {
                var result = waterLeakResourceService.GetByWaterLeakId(waterLeakId);
                foreach (var item in result.Data)
                {
                    
                    var urlHelper = new UrlHelper(Request);
                    item.Url = urlHelper.Link("DefaultApi", new { controller = "LeakContent", id = item.Id });
                    
                }
                return result;
            }

        }
        public string Get(double latPoint, double longPoint)
        {
            return "value: " + latPoint.ToString() + " " + longPoint.ToString();
        }
        private static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        public async Task Post()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());

            //access form data
            NameValueCollection formData = provider.FormData;

            //access files
            IList<HttpContent> files = provider.Files;

            //Example: reading a file's stream like below
            HttpContent file1 = files[0];
            Stream file1Stream = await file1.ReadAsStreamAsync();
            var resources = new List<WaterLeakResourceModel>();
            int waterLeakId = 0;
            int.TryParse(formData["waterLeakId"], out waterLeakId);
            if (waterLeakId != 0)
            {
                foreach (var item in provider.Files)
                {
                    Stream image = await file1.ReadAsStreamAsync();
                    if (item.Headers.ContentLength.Value > 0)
                    {
                        resources.Add(new WaterLeakResourceModel
                        {
                            MediaType = item.Headers.ContentType.MediaType,
                            Size = item.Headers.ContentLength.Value,
                            Resource = ReadFully(image)
                        });
                    }
                }
                using (var waterLeakResourceService = new WaterLeakResourceService())
                {
                    waterLeakResourceService.AddWaterLeakResource(waterLeakId, resources);
                }
            }
        }




        // PUT api/resource/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/resource/5
        public void Delete(int id)
        {
        }


        /*
        // POST api/files
        //you can post a files as multipart/form-data */
        //public async Task<HttpResponseMessage> Post()
        //{
        //    // Check if the request contains multipart/form-data.
        //    if (!Request.Content.IsMimeMultipartContent())
        //    {
        //        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        //    }

        //    string root = HttpContext.Current.Server.MapPath("~/App_Data");
        //    var provider = new MultipartFormDataStreamProvider(root);

        //    string value;

        //    try
        //    {
        //        // Read the form data and return an async data.
        //        var result = await Request.Content.ReadAsMultipartAsync(provider);

        //        // This illustrates how to get the form data.
        //        foreach (var key in provider.FormData.AllKeys)
        //        {
        //            foreach (var val in provider.FormData.GetValues(key))
        //            {
        //                // return multiple value from FormData
        //                if (key == "value")
        //                    value = val;
        //            }
        //        }

        //        if (result.FileData.Any())
        //        {
        //            // This illustrates how to get the file names for uploaded files.
        //            foreach (var file in result.FileData)
        //            {
        //                FileInfo fileInfo = new FileInfo(file.LocalFileName);
        //                if (fileInfo.Exists)
        //                {
        //                    //do somthing with file
        //                }
        //            }
        //        }


        //        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
        //        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
        //        return response;
        //    }
        //    catch (System.Exception e)
        //    {
        //        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        //    }
        //}

    }
}
